package org.thirdHero.wx.web;

import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ResourceLoader;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thirdHero.core.util.FileUtil;
import org.thirdHero.core.util.ResponseUtil;
import org.thirdHero.core.util.StringUtil;
import org.thirdHero.wx.config.SysConfigProperties;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * 文件上传
 */
@RestController
@RequestMapping("/buyer/file")
public class FileUploadController {
    @Resource
    private SysConfigProperties sysConfigProperties;
    @Resource
    ResourceLoader loader;

    /**
     * 文件上传
     * @param picture
     * @param model
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public Object upload(@RequestPart("file") MultipartFile picture, Model model) {
        String originalFilename = picture.getOriginalFilename();
        String prefix=originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        String pictureName = StringUtil.getUUID() + "." + prefix;
        try {
            String fileSavePath = sysConfigProperties.getUploadFilePath();
            if(!FileUtil.checkFileExists(fileSavePath+pictureName)){
                File file = new File(fileSavePath+pictureName);
                file.delete();
            }
            picture.transferTo(new File(fileSavePath + pictureName));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,"图片上传失败");
        }
        return ResponseUtil.ok(pictureName);
    }

    /**
     * 获得图片信息
     * @param fileName 文件名称
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/getImage/{fileName:.*}")
    public @ResponseBody byte[] getImage(@PathVariable String fileName) throws IOException {
        String imagePath = sysConfigProperties.getUploadFilePath()+fileName;
        if(FileUtil.checkFileExists(imagePath)){
           return null;
        }
        return IOUtils.toByteArray(loader.getResource("file:" + imagePath).getInputStream());
    }
}
